package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResultInfo login(String username, String password) {
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null) {
            return ResultInfo.error("用户不存在");
        }
        String passwordWithMd5 = SecureUtil.md5(password);
        if (!StringUtils.equals(passwordWithMd5, employee.getPassword())) {
            return ResultInfo.error("密码不正确");
        }
        if (employee.getStatus() == Employee.STATUS_DISABLE) {
            return ResultInfo.error("当前账户已经被禁用了");
        }
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String username) {
        return employeeMapper.findByName(username);
    }

    @Override
    public void saveEmployee(Employee employee) {
        //差什么补什么
        //雪花算法:(自学一下)
        Long id = IdUtil.getSnowflake(1, 1).nextId();
        employee.setId(id);//主键
        employee.setPassword(SecureUtil.md5("123"));//设置123为默认密码
        employee.setStatus(Employee.STATUS_ENABLE);//状态
        /*//todo 后期需要优化
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());
        //todo 临时写死,后期要从session中获取到当前操作用户
        employee.setCreateUser(1L);
        employee.setUpdateUser(1L);*/
        //2. 调用mapper保存
        employeeMapper.save(employee);
    }

    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }

    @Override
    public void update(Employee employee) {
        /*//todo 后期优化
        employee.setUpdateTime(new Date());
        employee.setUpdateUser(1L);*/

        //2. 调用mapper更新
        employeeMapper.update(employee);
    }

}
